package by.amakarevich.services.impl;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import by.amakarevich.dataaccess.UserAccountDao;
import by.amakarevich.datamodel.UserAccount;
import by.amakarevich.datamodel.UserAccount_;
import by.amakarevich.datamodel.enums.UserRole;
import by.amakarevich.services.UserAccountService;

@Service
public class UserAccountServiceImpl implements UserAccountService{
	
	@Inject
	private UserAccountDao userAccountDao;

	@Override
	public UserAccount get(Long id) {
		UserAccount entity = userAccountDao.getById(id);
		return entity;
	}

	@Override
	public void saveOrUpdate(UserAccount userAccount) {
		if (userAccount.getId() == null) {
			userAccountDao.insert(userAccount);
		} else {
			userAccountDao.update(userAccount);
		}
	}

	@Override
	public void delete(UserAccount userAccount) {
		userAccountDao.delete(userAccount.getId());

	}

	@Override
	public void deleteAll() {
		userAccountDao.deleteAll();
	}
	
	@Override
	public UserAccount getUserByEmail(String userName) {
		final List<UserAccount> allByFieldRestriction = userAccountDao.getAllByFieldRestriction(UserAccount_.email, userName);
		return !allByFieldRestriction.isEmpty() ? allByFieldRestriction.get(0) : null;
	}
	
	@Override
	public UserRole getRoles(Long userId) {
		UserAccount role = userAccountDao.getById(userId);
		return role.getRole();
	}
	
}
